import React, { Component, useRef, useEffect, useState } from 'react';
import { Drawer, Button, message, Select, Input, Space, Affix, Table, Popover, Form, Row, Col, DatePicker } from 'antd';
import { CmdbContent, HcpTableFilterBar } from '@/components';
import moment from 'moment';
import cmdbres from '@/data/cmdbres';
import request, { exportFile } from '@/utils/request';
import hcpUtils from '@/utils/hcpUtils';

const user = hcpUtils.getUser();
const { RangePicker } = DatePicker;
const RelationTable = ({ srcModule, destModule, cmInfo, onRelationFinish }) => {
    const [form] = Form.useForm();
    const [properties, setProperties] = useState({});
    const [loading, setLoading] = useState(false);
    const [tableData, setTableData] = useState([]);
    const [row, setRow] = useState({});
    const [tableHeaderFields, setTableHeaderFields] = useState([]);
    const [query_key, setQuery_key] = useState(''); //命名采用下划线方式方便直接传值
    const [query_keyType, setQuery_keyType] = useState('');
    const [inputHolderMess, setInputHolderMess] = useState('');
    const [fieldsEnum, setFieldsEnum] = useState([]);
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
    });

    useEffect(() => {
        queryTableHeaders();
        getTableData();
    }, [destModule]);

    const getTableData = async (params = { current: 1, pageSize: 10 }) => {
        if (!(destModule && destModule.displayModuleId)) {
            console.log('未获取到目的模型ID！');
            return;
        }
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryResourceList,
                data: {
                    cmModuleId: destModule.displayModuleId,
                    pageSize: params.pageSize,
                    pageNumber: params.current,
                    ...properties,
                    sort: {
                        create_time: 'DESC',
                    },
                },
            });
            setLoading(false);
            if (res && res.data) {
                setPagination((pagination) => ({
                    ...pagination,
                    current: res.pageNumber,
                    pageSize: res.pageSize,
                    total: res.total,
                }));
                let arr = [];
                res.data.map((item, index) => {
                    // let relationObj = relationIds.find(ids => item.cm_unid == ids.destId || item.cm_unid == ids.srcId );
                    // if(!relationObj) { //剔除已关联数据
                    //     item.key = index;
                    //     enumTranslate(item)
                    //     arr.push(item);
                    // }
                    item.key = index;
                    enumTranslate(item);
                    arr.push(item);
                });
                setTableData(arr);
            } else {
                setTableData([]);
            }
        } catch (error) {
            console.log(error);
        }
    };

    const onFinish = () => {
        setRow({});
        let query_value = form.getFieldValue([query_key]);
        if (query_keyType == 'date') {
            setProperties({
                queryFilter: {
                    GTE: {
                        // 大于等于号（>=）
                        [query_key]: query_value?.[0] ? query_value[0].format('YYYY-MM-DD') : undefined,
                    },
                    LTE: {
                        // 小于等于号(<=)
                        [query_key]: query_value?.[1] ? query_value[1].format('YYYY-MM-DD') : undefined,
                    },
                },
            });
        } else if (query_keyType == 'datetime') {
            if (!(query_value && query_value.length)) {
                setProperties({});
                return;
            }
            setProperties({
                timeConditions: [
                    {
                        field: query_key,
                        start: query_value[0].format('YYYY-MM-DD HH:mm:ss'),
                        end: query_value[1].format('YYYY-MM-DD HH:mm:ss'),
                    },
                ],
            });
        } else {
            setProperties({
                queryFilter: { LIKE: { [query_key]: query_value } },
            });
        }
    };

    useEffect(() => {
        getTableData();
    }, [properties]);

    const enumTranslate = (data) => {
        for (let fieldKey in data) {
            if (fieldsEnum[fieldKey]) {
                let enumValue = fieldsEnum[fieldKey];
                const translateState = enumValue[data[fieldKey]];
                if (translateState) {
                    data[fieldKey] = enumValue[data[fieldKey]];
                }
            }
        }
    };

    const queryTableHeaders = async () => {
        if (!(destModule && destModule.displayModuleId)) {
            console.log('未获取到目的模型ID！');
            return;
        }
        setLoading(true);
        try {
            const res = await request({
                ...cmdbres.queryTableHeader,
                params: {
                    cm_module_id: destModule.displayModuleId,
                },
            });
            setLoading(false);
            if (res && res.code == 200) {
                const fieldData = res.data;
                const filterArr = [];
                let enumValues = {};
                fieldData.fields.map((item, index) => {
                    let field = {
                        ...item,
                        key: item.propertyKey,
                        title: item.unit ? `${item.propertyName}(${item.unit})` : item.propertyName,
                        dataIndex: item.propertyKey,
                        width: 130,
                        copyable: true,
                        ellipsis: true,
                    };

                    if (['date', 'datetime'].includes(item.propertyType)) {
                        const formString = item.propertyType == 'date' ? 'YYYY-MM-DD' : 'YYYY-MM-DD HH:mm:ss';
                        field.render = (text, record) => hcpUtils.timeConversion(text, formString);
                    }

                    if (item.propertyType == 'enum' && field.woIsHidden === 0) {
                        let enumValueStr = item.propertyEnumValue.replace(/'/g, '"');
                        enumValues[field.key] = JSON.parse(enumValueStr);
                    }
                    setFieldsEnum(enumValues);

                    filterArr.push(field);
                });

                const operField = {
                    title: '操作',
                    fixed: 'right',
                    width: 80,
                    woIsSystem: 1,
                    woIsHidden: 1,
                    render: (text, record, index) => {
                        // const relationObj = relationIds.find(item => item.destId == record.cm_unid)
                        return (
                            <Space key={record.ruleId}>
                                <Popover content="关联">
                                    <span
                                        className="iconfont icon-bind"
                                        // disabled={idsLoading || relationObj}
                                        onClick={() => {
                                            handleRelation(record);
                                        }}
                                    />
                                </Popover>
                                {/* <Popover content="取消关联">
                                    <span
                                        className="iconfont icon-unbind"
                                        disabled={idsLoading || !relationObj}
                                        onClick={() => { handleUnRelation(record) }}
                                    />
                                </Popover> */}
                            </Space>
                        );
                    },
                };

                filterArr.push(operField);
                setTableHeaderFields(filterArr);
                if (filterArr.length) setSelectProperty(filterArr[0]);
            } else {
                setTableHeaderFields([]);
            }
        } catch (error) {
            console.log('getTableData -> error', error);
        }
    };

    const setSelectProperty = (field) => {
        setQuery_key(field?.propertyKey);
        setQuery_keyType(field?.propertyType);
        setInputHolderMess('请输入' + (field?.propertyName || ''));
    };

    useEffect(() => {
        if (!query_key && tableHeaderFields.length > 0) {
            setSelectProperty(tableHeaderFields[0]);
        }
    }, [query_key]);

    const resetScreen = () => {
        form.resetFields();
        if (tableHeaderFields.length > 0) {
            const field = tableHeaderFields[0];
            form.setFieldsValue({
                query_key: field?.propertyKey,
            });
            setSelectProperty(field);
        }
    };

    const onSelectChange = (propertyKey) => {
        const checkSelect = tableHeaderFields.find(function (val) {
            return val.propertyKey == propertyKey;
        });
        setSelectProperty(checkSelect);
    };

    const handleTableChange = (e) => {
        getTableData(e);
    };

    const handleRelation = async (record) => {
        // setLoading(true);
        let param = {
            srcModuleId: destModule.srcModuleId,
            srcModuleCode: destModule.srcModuleCode,
            srcModuleName: destModule.srcModuleName,
            srcId: destModule.isDest ? record.cm_unid : cmInfo.cm_unid,
            srcCmId: destModule.isDest ? record.cm_id : cmInfo.cm_id,
            associateType: destModule.associateType,
            destModuleId: destModule.destModuleId,
            destModuleCode: destModule.destModuleCode,
            destModuleName: destModule.destModuleName,
            destId: destModule.isDest ? cmInfo.cm_unid : record.cm_unid,
            destCmId: destModule.isDest ? record.cm_id : cmInfo.cm_id,
            mapping: destModule.mapping,
            author: user.staffName,
        };
        console.log(srcModule, destModule, cmInfo, record, param);

        let res = await request({
            ...cmdbres.createRelationData,
            data: param,
        });
        // setLoading(false);
        if (res && res.code == 200) {
            message.success('新增关联成功！');
            if (typeof onRelationFinish == 'function') onRelationFinish(res);
        }
    };

    return (
        <>
            <section>
                <HcpTableFilterBar
                    form={form}
                    resetClick={resetScreen}
                    onSearch={onFinish}
                    showSetFields={false}
                    items={[
                        {
                            field: { query_key },
                            style: { float: 'none', margin: '0 0 0 8px' },
                            component: (
                                <Form.Item label="条件筛选" style={{ margin: 0 }}>
                                    <Row>
                                        <Col span={8}>
                                            <Form.Item name="query_key" noStyle>
                                                {query_key ? (
                                                    <Select
                                                        style={{ width: '98%', textAlign: 'left' }}
                                                        defaultValue={query_key}
                                                        onChange={onSelectChange}
                                                        getPopupContainer={(triggerNode) => triggerNode.parentElement}
                                                    >
                                                        {tableHeaderFields
                                                            ?.filter((item) => item.propertyName)
                                                            ?.map((item, index) => {
                                                                return (
                                                                    <Select.Option
                                                                        value={item.propertyKey}
                                                                        defaultValue={tableHeaderFields[0].propertyKey}
                                                                        key={index}
                                                                    >
                                                                        {item.propertyName}
                                                                    </Select.Option>
                                                                );
                                                            })}
                                                    </Select>
                                                ) : null}
                                            </Form.Item>
                                        </Col>
                                        <Col span={16}>
                                            {query_keyType == 'date' ? (
                                                <Form.Item key={query_key} name={query_key} noStyle>
                                                    <RangePicker format="YYYY-MM-DD" />
                                                </Form.Item>
                                            ) : query_keyType == 'datetime' ? (
                                                <Form.Item key={query_key} name={query_key} noStyle>
                                                    <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
                                                </Form.Item>
                                            ) : (
                                                <Form.Item key={query_key} name={query_key} noStyle>
                                                    <Input
                                                        allowClear
                                                        maxLength={50}
                                                        placeholder={inputHolderMess}
                                                        style={{ width: 370 }}
                                                    />
                                                </Form.Item>
                                            )}
                                        </Col>
                                    </Row>
                                </Form.Item>
                            ),
                        },
                    ]}
                />
            </section>
            <Table
                rowKey={(record) => record.cm_unid}
                columns={tableHeaderFields}
                loading={loading}
                dataSource={tableData}
                scroll={{ x: '100%', y: 300 }}
                pagination={{
                    showSizeChanger: true,
                    showQuickJumper: {
                        goButton: <Button style={{ margin: '0 10px' }}>确定</Button>,
                    },
                    ...pagination,
                }}
                onChange={handleTableChange}
                hideSetting
            />
        </>
    );
};

export default RelationTable;
